from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from goods.models import SPU,Brand,GoodsCategory
from . import spu_serializers
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings

#1,spu
class SPUViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    queryset = SPU.objects.all()
    serializer_class = spu_serializers.SPUSerializer

#2,spu brand
class SPUBrandListView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = spu_serializers.SPUBrandSerializer

#3,spu category(一级分类)
class SPUCategoryListView(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent=None).all()
    serializer_class = spu_serializers.SPUCategorySerializer

#4,spu category(二级,三级分类)
class SubsCategoryListView(ListAPIView):
    serializer_class = spu_serializers.SPUCategorySerializer

    #1,提供数据源,获取子分类信息(二级,三级)
    def get_queryset(self):
        #1,获取父分类的id
        category_id = self.kwargs.get("category_id")

        #2,获取子分类
        return GoodsCategory.objects.filter(parent_id=category_id).all()

#5,spu detail image
class SPUDetailImageView(APIView):
    def post(self,request):
        #1,获取参数
        image = request.FILES.get("image")

        #2,校验参数
        if not image:
            return Response("参数不全",status=400)

        #3,图片上传
        client = Fdfs_client(settings.CONFIG_URL)

        result = client.upload_by_buffer(image.read())

        if result["Status"] != "Upload successed.":
            return Response("上传失败", status=400)


        #4,返回响应
        img_url = settings.BASE_URL + result["Remote file_id"]
        return Response({"img_url":img_url})